package com.itic.appbase.applications.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.usersmall.service.UsersMallService;
import com.itic.mall.system.ywym.client.persistence.model.YwymClient;
import com.itic.mall.system.ywym.client.persistence.model.YwymClientExample;
import com.itic.mall.system.ywym.client.service.YwymClientService;
import com.itic.mall.system.ywym.timer.persistence.model.YwymTimer;
import com.itic.mall.system.ywym.timer.persistence.model.YwymTimerExample;
import com.itic.mall.system.ywym.timer.service.YwymTimerService;

import net.sf.json.JSONObject;

public class SystemWebSocketHandler implements WebSocketHandler{
	    private static final Logger logger;
	    //商品过滤字段
	    protected static String[] commonIgnoreProperties = new String[] { "createUser", "isEffective", "updateTime", "note",
	  			"createTime", "orgCode" };

	    private static final ArrayList<WebSocketSession> users;

	    static {
	        users = new ArrayList<>();
	        logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
	    }

	    @Autowired
	    private YwymTimerService ywymTimerService;
	    @Autowired
	    private YwymClientService ywymClientService;
	    @Autowired
	    private UsersMallService usersMallService;

	    @Override
	    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
	        logger.debug("connect to the websocket success......");
	        users.add(session);
	        String userId = (String) session.getAttributes().get(Constants.WS_USER_NAME);
	        if(userId!= null){
	        	
	        	HashMap<String,Object> dataMap = new HashMap<String,Object>();
	        	//添加上线信息
	        	onLine(userId);
	        	
	        	//判断当前终端是否有设置的时间
	        	YwymTimerExample example = new YwymTimerExample();
	        	example.setOrderByClause("START_TIME ASC");
	        	com.itic.mall.system.ywym.timer.persistence.model.YwymTimerExample.Criteria criteria = example.createCriteria();
	        	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	        	criteria.andUserIdEqualTo(userId);
	        	
	        	List<YwymTimer> list = ywymTimerService.list(example);
	        	if( list.size()==0 ){
	        		list = getDefaultTimer();
	        	}
	        	
	        	dataMap.put("list", ValueHelper.tranList2MapList(list,commonIgnoreProperties));
	        	dataMap.put("currentTime", DateHelper.getDateTime());
	        	JSONObject fromObject = JSONObject.fromObject(dataMap);
	        	//发送消息给客户端
	        	TextMessage textMessage = new TextMessage( fromObject.toString() );
	        	sendMessageToUser(userId, textMessage);
	        }
	    }

		@Override
	    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {

	        //sendMessageToUsers();
	    }

	    @Override
	    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
	        if(session.isOpen()){
	            session.close();
	        }
	        logger.debug("websocket connection closed......");
	        users.remove(session);
	    }

	    @Override
	    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
	        logger.debug("websocket connection closed......");
	        users.remove(session);
	        String userId = (String) session.getAttributes().get(Constants.WS_USER_NAME);
	        downLine(userId);
	    }

	    @Override
	    public boolean supportsPartialMessages() {
	        return false;
	    }

	    /**
	     * 给所有在线用户发送消息
	     *
	     * @param message
	     */
	    public void sendMessageToUsers(TextMessage message) {
	        for (WebSocketSession user : users) {
	            try {
	                if (user.isOpen()) {
	                    user.sendMessage(message);
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }

	    /**
	     * 给某个用户发送消息
	     *
	     * @param userName
	     * @param message
	     */
	    public void sendMessageToUser(String userName, TextMessage message) {
	        for (WebSocketSession user : users) {
	            if (user.getAttributes().get(Constants.WS_USER_NAME).equals(userName)) {
	                try {
	                    if (user.isOpen()) {
	                        user.sendMessage(message);
	                    }
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	                break;
	            }
	        }
	    }
	    
	    
	    /**
	     * 添加上线信息
	     * @param userId
	     */
	    private void onLine( String userId ) {
			//查找数据库有没有
	    	YwymClientExample example = new YwymClientExample();
	    	com.itic.mall.system.ywym.client.persistence.model.YwymClientExample.Criteria criteria = example.createCriteria();
	    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	    	criteria.andUserIdEqualTo(userId);
	    	
	    	List<YwymClient> list = ywymClientService.list(example);
	    	if( list.size()>0 ){
	    		YwymClient ywymClient = list.get(0);
	    		ywymClient.setStatus("上线");
	    		ywymClientService.edit(ywymClient);
	    	}else{
	    		YwymClient ywymClient = new YwymClient();
	    		ywymClient.setUserId(userId);
	    		ywymClient.setStatus("上线");
	    		UsersMall usersMall = usersMallService.get(userId);
	    		ywymClient.setUserName(usersMall.getUserNickName());
	    		ywymClient.setUserPhone(usersMall.getUserPhone());
	    		ywymClientService.add(ywymClient);
	    	}
		}
	    
	    /**
	     * 添加下线信息
	     * @param userId
	     */
	    private void downLine( String userId ){
	    	//查找数据库有没有
	    	YwymClientExample example = new YwymClientExample();
	    	com.itic.mall.system.ywym.client.persistence.model.YwymClientExample.Criteria criteria = example.createCriteria();
	    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	    	criteria.andUserIdEqualTo(userId);
	    	
	    	List<YwymClient> list = ywymClientService.list(example);
	    	if( list.size()>0 ){
	    		YwymClient ywymClient = list.get(0);
	    		ywymClient.setStatus("离线");
	    		ywymClientService.edit(ywymClient);
	    	}
	    }

		/**
	     * 获取默认时间配置
	     * @return
	     */
	    private List<YwymTimer> getDefaultTimer() {
	    	YwymTimerExample example = new YwymTimerExample();
        	example.setOrderByClause("START_TIME ASC");
        	com.itic.mall.system.ywym.timer.persistence.model.YwymTimerExample.Criteria criteria = example.createCriteria();
        	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        	criteria.andUserIdIsNull();
        	List<YwymTimer> list = ywymTimerService.list(example);
        	return list;
		}
}
